{% extends 'base.html' %}
{% load static %}

{% block title %}运行测试套件: {{ test_suite.name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>测试套件运行</h2>
                <div>
                    <a href="{% url 'test_suite_detail' test_suite.pk %}" class="btn btn-outline-secondary me-2">
                        <i class="bi bi-arrow-left"></i> 返回
                    </a>
                    <button type="button" id="runButton" class="btn btn-primary" disabled>
                        <i class="bi bi-play-fill"></i> 运行
                    </button>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">运行配置</h5>
                </div>
                <div class="card-body">
                    <form id="runForm" method="post">
                        {% csrf_token %}
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="name" class="form-label">名称</label>
                                    <input type="text" class="form-control" id="name" name="name"
                                           value="Suite run: {{ test_suite.name }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="environment" class="form-label">默认环境</label>
                                    <select class="form-select" id="environment" name="environment" required>
                                        <option value="">选择环境</option>
                                        {% for env in environments %}
                                            <option value="{{ env.id }}" data-base-url="{{ env.base_url }}">
                                                {{ env.name }} ({{ env.base_url }})
                                            </option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">测试用例列表</h5>
                </div>
                <div class="card-body">
                    {% if test_suite_cases %}
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Order</th>
                                        <th>测试用例</th>
                                        <th>请求方法</th>
                                        <th>URL</th>
                                        <th>环境</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for suite_case in test_suite_cases %}
                                        <tr>
                                            <td>{{ suite_case.order }}</td>
                                            <td>
                                                <a href="{% url 'test_case_detail' suite_case.test_case.pk %}"
                                                   class="text-decoration-none">
                                                    {{ suite_case.test_case.name }}
                                                </a>
                                            </td>
                                            <td>
                                                <span class="badge bg-{% if suite_case.test_case.request_method == 'GET' %}primary{% elif suite_case.test_case.request_method == 'POST' %}success{% elif suite_case.test_case.request_method == 'PUT' %}warning{% elif suite_case.test_case.request_method == 'DELETE' %}danger{% else %}secondary{% endif %}">
                                                    {{ suite_case.test_case.request_method }}
                                                </span>
                                            </td>
                                            <td>
                                                <code>{{ suite_case.test_case.request_url }}</code>
                                            </td>
                                            <td>
                                                <select class="form-select form-select-sm case-environment"
                                                        name="case_environment_{{ suite_case.test_case.id }}"
                                                        data-case-id="{{ suite_case.test_case.id }}">
                                                    <option value="">使用默认环境</option>
                                                    {% for env in environments %}
                                                        <option value="{{ env.id }}" data-base-url="{{ env.base_url }}">
                                                            {{ env.name }}
                                                        </option>
                                                    {% endfor %}
                                                </select>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="bi bi-inbox display-4 text-muted"></i>
                            <p class="text-muted mt-2">该测试套件中没有测试用例</p>
                            <a href="{% url 'test_suite_detail' test_suite.pk %}" class="btn btn-primary">
                                添加测试用例
                            </a>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 运行确认模态框 -->
<div class="modal fade" id="runConfirmModal" tabindex="-1" aria-labelledby="runConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="runConfirmModalLabel">确认运行测试套件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要运行测试套件 "<strong>{{ test_suite.name }}</strong>" 吗？</p>
                <div id="runSummary"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmRunButton">
                    <i class="bi bi-play-fill"></i> 确认运行
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 运行中模态框 -->
<div class="modal fade" id="runningModal" tabindex="-1" aria-labelledby="runningModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="runningModalLabel">正在运行测试套件</h5>
            </div>
            <div class="modal-body text-center">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p>测试套件正在后台执行，请稍候...</p>
                <p class="text-muted">您可以在测试运行页面查看详细进度</p>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const environmentSelect = document.getElementById('environment');
    const runButton = document.getElementById('runButton');
    const runForm = document.getElementById('runForm');
    const caseEnvironmentSelects = document.querySelectorAll('.case-environment');
    const runConfirmModal = new bootstrap.Modal(document.getElementById('runConfirmModal'));
    const runningModal = new bootstrap.Modal(document.getElementById('runningModal'));
    const confirmRunButton = document.getElementById('confirmRunButton');
    const runSummary = document.getElementById('runSummary');

    // 存储键
    const STORAGE_KEY = 'easytesting_suite_run_environment';
    const CASE_ENV_STORAGE_KEY = 'easytesting_case_environments';

    // 加载保存的环境选择
    function loadSavedEnvironment() {
        const savedEnv = localStorage.getItem(STORAGE_KEY);
        if (savedEnv && environmentSelect) {
            environmentSelect.value = savedEnv;
            updateRunButtonState();
        }

        // 加载测试用例环境选择
        const savedCaseEnvs = localStorage.getItem(CASE_ENV_STORAGE_KEY);
        if (savedCaseEnvs) {
            try {
                const caseEnvs = JSON.parse(savedCaseEnvs);
                caseEnvironmentSelects.forEach(select => {
                    const caseId = select.dataset.caseId;
                    if (caseEnvs[caseId]) {
                        select.value = caseEnvs[caseId];
                    }
                });
            } catch (e) {
                console.error('Failed to load saved case environments:', e);
            }
        }
    }

    // 保存环境选择
    function saveEnvironment() {
        if (environmentSelect.value) {
            localStorage.setItem(STORAGE_KEY, environmentSelect.value);
        }

        // 保存测试用例环境选择
        const caseEnvs = {};
        caseEnvironmentSelects.forEach(select => {
            const caseId = select.dataset.caseId;
            if (select.value) {
                caseEnvs[caseId] = select.value;
            }
        });
        localStorage.setItem(CASE_ENV_STORAGE_KEY, JSON.stringify(caseEnvs));
    }

    // 更新运行按钮状态
    function updateRunButtonState() {
        runButton.disabled = !environmentSelect.value;
    }

    // 生成运行摘要
    function generateRunSummary() {
        const selectedEnv = environmentSelect.options[environmentSelect.selectedIndex];
        const envName = selectedEnv ? selectedEnv.text : '';

        let customEnvCount = 0;
        caseEnvironmentSelects.forEach(select => {
            if (select.value) {
                customEnvCount++;
            }
        });

        let summary = `<p><strong>默认环境:</strong> ${envName}</p>`;
        if (customEnvCount > 0) {
            summary += `<p><strong>自定义环境的测试用例:</strong> ${customEnvCount} 个</p>`;
        }
        summary += `<p><strong>总测试用例数:</strong> ${caseEnvironmentSelects.length} 个</p>`;

        runSummary.innerHTML = summary;
    }

    // 事件监听器
    environmentSelect.addEventListener('change', function() {
        updateRunButtonState();
        saveEnvironment();
    });

    caseEnvironmentSelects.forEach(select => {
        select.addEventListener('change', saveEnvironment);
    });

    runButton.addEventListener('click', function() {
        if (!environmentSelect.value) {
            alert('请先选择环境');
            return;
        }

        generateRunSummary();
        runConfirmModal.show();
    });

    confirmRunButton.addEventListener('click', function() {
        runConfirmModal.hide();

        // 添加测试用例环境选择到表单
        caseEnvironmentSelects.forEach(select => {
            if (select.value) {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = select.name;
                hiddenInput.value = select.value;
                runForm.appendChild(hiddenInput);
            }
        });

        // 显示运行中模态框
        runningModal.show();

        // 提交表单
        runForm.submit();
    });

    // 初始化
    loadSavedEnvironment();
});
</script>

<style>
.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
}

.table td {
    vertical-align: middle;
}

.form-select-sm {
    font-size: 0.875rem;
}

.badge {
    font-size: 0.75rem;
}

code {
    font-size: 0.875rem;
    color: #e83e8c;
    background-color: #f8f9fa;
    padding: 0.125rem 0.25rem;
    border-radius: 0.25rem;
}

.spinner-border {
    width: 3rem;
    height: 3rem;
}

.modal-body .text-muted {
    font-size: 0.9rem;
}
</style>
{% endblock %}
